package uscdb.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import uscdb.pageModel.DataGrid;
import uscdb.pageModel.Json;
import uscdb.pageModel.PageHelper;
import uscdb.pageModel.Script;
import uscdb.service.ScriptServiceI;
import uscdb.util.ConfigUtil;
import uscdb.util.StringUtil.StringUtil;

/**
 * script 管理控制器
 */
@Controller
@RequestMapping("/scriptController")
public class ScriptController extends BaseController {

	private static final Logger logger = Logger.getLogger(ScriptController.class);

	@Autowired
	private ScriptServiceI scriptService;

	/**
	 * 跳转到 script 管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/manager")
	public String manager(HttpServletRequest request) {
		return "/script/script";
	}
	
	/**
	 * 跳转到查看页面
	 * 
	 * @return
	 */
	@RequestMapping("/view")
	public String view(HttpServletRequest request, String id) {
		Script script = scriptService.get(id);
		request.setAttribute("script",script);
		return "/script/scriptView";
	}
	
	/**
	 * 跳转到修改页面
	 * 
	 * @return
	 */
	@RequestMapping("/editPage")
	public String editPage(HttpServletRequest request, String id) {
		Script script = scriptService.get(id);
		request.setAttribute("script",script);
		return "/script/scriptEdit";
	}
	
	/**
	 * 修改
	 * 
	 * @param script
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(Script script) {
		Json j = new Json();
		try {
			scriptService.edit(script);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return j;
	}

	/**
	 * 获取 script 数据表格
	 * 
	 * @param script
	 *            页面对象
	 * @param ph
	 *            分页对象
	 * @return
	 */
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(Script script, PageHelper ph) {
		return scriptService.dataGrid(script, ph);
	}

	@ResponseBody
	@RequestMapping("/importScriptExcel")
	public Json importScriptExcel(HttpServletResponse response, HttpServletRequest request, HttpSession session) {
		Json json = new Json();
		try {
			// 文件保存目录路径
			String savePath = session.getServletContext().getRealPath("/") + "attached/import/";
			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			// 记住，下面还有一处地方需要修改
			extMap.put("excelFile", ConfigUtil.get("excelFile"));
			long maxSize = Long.parseLong(ConfigUtil.get("maxFileSize")); // 允许上传最大文件大小(字节)
			if (!ServletFileUpload.isMultipartContent(request)) {
				json.setMsg("请选择文件！");
				return json;
			}
			// 检查目录
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				uploadDir.mkdirs();
			}
			// 检查目录写权限
			if (!uploadDir.canWrite()) {
				json.setMsg("上传目录没有写权限！");
				return json;
			}
			// 增加日期目录，便于归档
			SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthDf = new SimpleDateFormat("MM");
			SimpleDateFormat dateDf = new SimpleDateFormat("dd");
			Date date = new Date();
			String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
			savePath += ymd;
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			if (ServletFileUpload.isMultipartContent(request)) {// 判断表单是否存在enctype="multipart/form-data"
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				try {
					List<FileItem> items = upload.parseRequest(request);
					// 上传的文件流
					File uploadedFile = null;
					// 保存表单值的对象，目前是保存 versionname
					Script script = new Script();
					for (FileItem item : items) {
						String fileName = item.getName();
						if (!item.isFormField()) {
							// 检查文件大小
							if (item.getSize() > maxSize) {
								json.setMsg("上传文件大小超过限制！(允许最大[" + maxSize + "]字节，您上传了[" + item.getSize() + "]字节)");
								return json;
							}
							// 检查扩展名
							String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
							if (!Arrays.<String> asList(extMap.get("excelFile").split(",")).contains(fileExt)) {
								json.setMsg(StringUtil.speakToUser("import"));
								return json;
							}
							String newFileName = UUID.randomUUID().toString() + "." + fileExt;
							try {
								uploadedFile = new File(savePath, newFileName);
								item.write(uploadedFile);
							} catch (Exception e) {
								logger.error(e.getMessage(), e);
								json.setMsg("上传文件失败！");
								return json;
							}
						} else {
							String name = item.getFieldName();
							if ("versionName".equals(name)) {
								String versionName = item.getString();
								script.setVersionName(versionName);
							}
						}
					}
					String resultString = scriptService.importScriptExcel(uploadedFile, script);
					json.setMsg(resultString);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}

}
